//
//  MainTabBar.swift
//  haiTwitter
//
//  Created by mohen on 15/3/13.
//  Copyright (c) 2015年 mohen. All rights reserved.
//

import UIKit

class MainTabBar: UITabBar {

    var composedButtonClick: (() -> ())?
    
    override func awakeFromNib() {
        self.addSubview(composeBtn!)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        setupButtonsFrame()
    }
    
    func setupButtonsFrame() {
        
        let w = self.bounds.width / CGFloat(buttonCount)
        let h = self.bounds.height
        
        var index = 0
        
        for view in self.subviews as! [UIView] {
            if view is UIControl && !(view is UIButton) {
                
                let r = CGRectMake(CGFloat(index) * w, 0, w, h)
                view.frame = r
                
                index++
                if index == 2 {
                    index++
                }
            }
        }
        
        // 3. 设置加号按钮的位置
        composeBtn?.frame = CGRectMake(0, 0, w, h)
        
        // 注意 composeBtn?.center 系统自动做了处理，所以当手动设置的时候要 h * 0.5
        println(composeBtn?.center)
        composeBtn?.center = CGPointMake(self.center.x, h * 0.5)
    }
    
    // 按钮总数
    let buttonCount = 5
    // 懒加载
    lazy var composeBtn: UIButton? = {
        
        let btn = UIButton()
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        // 添加按钮的监听方法
        btn.addTarget(self, action: "clickCompose", forControlEvents: UIControlEvents.TouchUpInside)
        
        return btn
    }()
    
    func clickCompose() {
        println("come here")
        
        if composedButtonClick != nil {
            composedButtonClick!()
        }
    }
}
